import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_09_game/base/widget/base_list_more_get_builder.dart';
import 'package:flutter_09_game/config/app_color.dart';
import 'package:flutter_09_game/generated/assets.dart';
import 'package:flutter_09_game/generated/locales.g.dart';
import 'package:flutter_09_game/pages/deposit/models/model_record_team_commission.dart';
import 'package:flutter_09_game/user/app_user_manager.dart';
import 'package:flutter_09_game/utils/extensions/num_ext.dart';
import 'package:flutter_09_game/utils/utils_other.dart';
import 'package:flutter_09_game/utils/utils_time.dart';
import 'package:flutter_09_game/widgets/btn_dropdown.dart';
import 'package:flutter_09_game/widgets/button/debounce_gesture_detector.dart';
import 'package:flutter_09_game/widgets/image/auto_image.dart';
import 'package:flutter_09_game/widgets/image/image_view.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import 'deposit_record_team_commission_logic.dart';

class DepositRecordTeamCommissionPage extends StatelessWidget {
  DepositRecordTeamCommissionPage({super.key, required this.tag});
  // https://api.798ys.xyz/api/battle-royale/team-member-statistics
  // https://api.798ys.xyz/api/user/team-member-statistics
  final String tag;
  late final DepositRecordTeamCommissionLogic logic =
      Get.put(DepositRecordTeamCommissionLogic(), tag: tag);

  @override
  Widget build(BuildContext context) {
    return BaseListMoreGetBuilder<DepositRecordTeamCommissionLogic>(
      init: logic,
      tag: tag,
      bodyTopViewBuilder: (_) {
        return _buildNotTeamTop();
      },
      builder: (l) {
        return ListView.builder(
            padding: EdgeInsets.only(top: 24.w, bottom: 24.w),
            itemCount: logic.list.length,
            itemBuilder: itemBuilder);
      },
    );
  }

  /// 构建列表项
  Widget itemBuilder(BuildContext context, int index) {
    final item = logic.list[index] as ModelRecordTeamCommission;

    return Container(
      margin: EdgeInsets.symmetric(
        horizontal: 16.w,
      ).copyWith(bottom: 16.w),
      padding: EdgeInsets.symmetric(horizontal: 8.w),
      decoration: BoxDecoration(
        color: AppColor.navBgColor,
        borderRadius: BorderRadius.circular(12.w),
      ),
      child: Column(
        children: [
          12.verticalSpaceFromWidth,
          Row(
            children: [
              // 头像

              Container(
                  width: 44.w,
                  height: 44.w,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(22.w),
                    border: Border.all(
                      color: AppColor.color22242A,
                      width: 1.w,
                    ),
                  ),
                  child: Stack(
                    children: [
                      Positioned.fill(
                          child: ImageView(
                        imageUrl: item.userAvatar,
                        radius: 22.w,
                        fit: BoxFit.cover,
                      )),
                      Positioned(
                        bottom: 0,
                        right: 0,
                        child: Container(
                          width: 16.w,
                          height: 16.w,
                          decoration: BoxDecoration(
                            color: item.isOnline == true
                                ? AppColor.homePrizePoolBgIndicator
                                    .withOpacity(0.12)
                                : AppColor.textPrimary.withOpacity(0.08),
                            shape: BoxShape.circle,
                          ),
                          child: Center(
                            child: Container(
                              width: 8.w,
                              height: 8.w,
                              decoration: BoxDecoration(
                                color: item.isOnline == true
                                    ? AppColor.homePrizePoolIndicator
                                    : AppColor.textPrimary.withOpacity(0.3),
                                shape: BoxShape.circle,
                              ),
                            ),
                          ),
                        ),
                      )
                    ],
                  )),
              12.horizontalSpace,
              // 用户信息
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    // 用户名和直属人数
                    Row(
                      children: [
                        Flexible(
                          child: Text(
                            item.username ?? '--',
                            style: TextStyle(
                              fontFamily: 'PingFang SC',
                              fontSize: 12.sp,
                              fontWeight: FontWeight.w500,
                              color: AppColor.textPrimary.withOpacity(0.94),
                            ),
                          ),
                        ),
                        8.horizontalSpace,
                        // 直属人数

                        AutoImage(
                          Assets.promotionCommissionUser,
                          width: 16.w,
                          height: 16.w,
                        ),
                        // 4.horizontalSpace,
                        Text(
                          '${(item.memberCount ?? 0) + 1}',
                          style: TextStyle(
                            fontFamily: 'PingFang SC',
                            fontSize: 14.sp,
                            fontWeight: FontWeight.w400,
                            color: AppColor.textPrimary.withOpacity(0.7),
                          ),
                        ),
                      ],
                    ),
                    4.verticalSpaceFromWidth,
                    // 会员ID
                    DebounceGestureDetector(
                        onTap: () =>
                            UtilsOther.copyMemberId(item.userIdentity ?? ''),
                        child: Row(
                          children: [
                            Flexible(
                              child: Text(
                                '${LocaleKeys.memberId.tr}：${item.userIdentity ?? '--'}',
                                style: TextStyle(
                                  fontFamily: 'PingFang SC',
                                  fontSize: 12.sp,
                                  fontWeight: FontWeight.w400,
                                  color: AppColor.textPrimary.withOpacity(0.7),
                                ),
                              ),
                            ),
                            4.horizontalSpace,
                            AutoImage(
                              Assets.promotionCommissionCopy,
                              width: 16.w,
                              height: 16.w,
                            ),
                          ],
                        )),
                    4.verticalSpaceFromWidth,
                    Text(
                      '${LocaleKeys.betAddress.tr}：${UtilsOther.formatWithdrawAddress(item.withdrawAddress)}',
                      style: TextStyle(
                        fontFamily: 'PingFang SC',
                        fontSize: 12.sp,
                        fontWeight: FontWeight.w400,
                        color: AppColor.textPrimary.withOpacity(0.7),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),

          24.verticalSpaceFromWidth,
          // Text(
          //   getGameType(item), //      LocaleKeys.webSettlement.tr,
          //   style: TextStyle(
          //       fontSize: 14.sp,
          //       fontWeight: FontWeight.w500,
          //       color: AppColor.textPrimary.withOpacity(0.7)),
          // ),
          // 4.verticalSpaceFromWidth,
          // 顶部金额和币种区域
          _buildAmountSection(item),

          24.verticalSpaceFromWidth,
          // 信息行区域
          _buildInfoRows(item),
          12.verticalSpaceFromWidth,
        ],
      ),
    );
  }

  /// 构建金额和币种区域
  Widget _buildAmountSection(ModelRecordTeamCommission item) {
    // final amount = (item.amount ?? 0) / 1000000.0; // 转换为实际金额
    // final isPositive = amount >= 0;
    int amount = (item.winAmount ?? 0) - (item.amount ?? 0);
    return Row(
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        // 金额显示
        Text(
          '${amount > 0 ? '+' : ''}${amount.formatWallet()}',
          style: TextStyle(
              fontSize: 20.sp,
              fontWeight: FontWeight.w900,
              color: amount > 0
                  ? AppColor.homePrizePoolIndicator
                  : (amount == 0 && item.dataSource == 'battle_royale')
                      ? AppColor.colorEDA247
                      : AppColor.gameResultEven

              // color: item.status == 1
              //     ? AppColor.homePrizePoolIndicator
              //     : item.status == 0
              //         ? AppColor.gameResultEven
              //         : AppColor.colorEDA247,
              ),
        ),
        4.horizontalSpace,

        // 币种图标和文字
        Row(
          children: [
            AutoImage(
              UtilsOther().getAmountTagIcon(item.symbol),
              width: 20.w,
              height: 20.w,
            ),
            4.horizontalSpace,
            Text(
              item.symbol ?? '',
              style: TextStyle(
                fontSize: 14.sp,
                fontWeight: FontWeight.w400,
                color: AppColor.textPrimary.withOpacity(0.7),
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建信息行区域
  Widget _buildInfoRows(ModelRecordTeamCommission item) {
    return Column(
      children: [
        Row(
          children: [
            Expanded(
              child: _buildInfoRow(
                label: LocaleKeys.participateGame.tr,
                value: item.gameName ?? '',
              ),
            ),
            4.horizontalSpace,
            Expanded(
              child: _buildInfoRow(
                label: LocaleKeys.betType.tr,
                value: item.dataSource == 'internal' && item.joinType == 1
                    ? LocaleKeys.externalTransfer.tr
                    : LocaleKeys.internalBet.tr,
              ),
            ),
          ],
        ),
        4.verticalSpaceFromWidth,

        _buildInfoRow(
          label: LocaleKeys.betOrderNumber.tr,
          value: item.identity ?? '',
          showCopy: true,
        ),
        // 4.verticalSpaceFromWidth,

        4.verticalSpaceFromWidth,
        _buildInfoRow(
            label: LocaleKeys.accountBalance.tr,
            value: item.walletBalance.formatWallet(),
            rightValue: item.symbol),
        4.verticalSpaceFromWidth,
        _buildInfoRow(
          label: LocaleKeys.time.tr,
          value: UtilsTime.depositFormatTime(item.createdAt),
        ),
      ],
    );
  }

  /// 构建信息行
  Widget _buildInfoRow({
    required String label,
    required String value,
    bool showCopy = false,
    String? rightValue,
  }) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 12.w, vertical: 12.w),
      decoration: BoxDecoration(
        color: AppColor.homeTabBackground,
        borderRadius: BorderRadius.circular(8.w),
      ),
      child: Row(
        children: [
          // 标签
          Expanded(
            child: Text(
              label,
              style: TextStyle(
                fontSize: 12.sp,
                fontWeight: FontWeight.w400,
                color: AppColor.textPrimary.withOpacity(0.7),
              ),
            ),
          ),
          // 值和复制按钮
          Row(
            children: [
              Text(
                value,
                style: TextStyle(
                  fontSize: 12.sp,
                  fontWeight: FontWeight.w600,
                  color: AppColor.textPrimary,
                ),
              ),
              if (showCopy) ...[
                4.horizontalSpace,
                GestureDetector(
                  onTap: () => UtilsOther.copyMemberId(value),
                  child: AutoImage(
                    Assets.promotionCommissionCopy,
                    width: 16.w,
                    height: 16.w,
                  ),
                ),
              ],
              Visibility(
                  visible: (rightValue ?? '').isNotEmpty,
                  child: Text(
                    rightValue ?? "",
                    style: TextStyle(
                      fontSize: 12.sp,
                      color: AppColor.textPrimary.withOpacity(0.7),
                    ),
                  ).marginOnly(left: 4.w))
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildNotTeamTop() {
    Widget inputWidget =
        _buildInput(logic.idController, LocaleKeys.memberId.tr);
    Widget orderInputWidget =
        _buildInput(logic.idRegController, LocaleKeys.betOrderNumber.tr);

    Widget symbolWidget = Obx(() => _buildTopDropdown([
          LocaleKeys.allCoins.tr,
          ...AppUserManager().walletList.map((f) => f.symbol ?? '')
        ],
            value: logic.symbolRx.value.isEmpty
                ? LocaleKeys.allCoins.tr
                : logic.symbolRx.value,
            mainAxisAlignment: MainAxisAlignment.start, onChanged: (value) {
          if (value == LocaleKeys.allCoins.tr) {
            logic.symbolRx.value = '';
          } else {
            logic.symbolRx.value = value;
          }
          logic.refreshController.requestRefresh();
        }));

    return Column(
      children: [
        Container(
          padding: EdgeInsets.all(16.w).copyWith(bottom: 24.w),
          decoration: BoxDecoration(
            color: AppColor.navBgColor,
            borderRadius: BorderRadius.only(
              bottomLeft: Radius.circular(30.w),
              bottomRight: Radius.circular(30.w),
            ),
          ),
          child: Obx(() {
            return Column(
              children: [
                Row(
                  children: [
                    Expanded(child: symbolWidget),
                    4.horizontalSpace,
                    Expanded(
                        child: Obx(() => _buildTopDropdown(logic.statusRows,
                                value: logic.statusRx.value,
                                mainAxisAlignment: MainAxisAlignment.start,
                                onChanged: (value) {
                              logic.statusRx.value = value;
                              // AppUserManager().selectUserWallet(value);
                              logic.refreshController.requestRefresh();
                            }))),
                    4.horizontalSpace,
                    Expanded(
                        child: _buildTopDropdown([
                      LocaleKeys.today.tr,
                      LocaleKeys.yesterday.tr,
                      LocaleKeys.threeDays.tr,
                      LocaleKeys.sevenDays.tr,
                      LocaleKeys.custom.tr,
                    ], btnColor: AppColor.primary, value: logic.timeRx.value,
                            onChanged: (value) {
                      logic.updateTimeSelection(value);
                    })),
                    // 4.horizontalSpace,
                    // Expanded(
                    //     child: type == LocaleKeys.game.tr
                    //         ? inputWidget
                    //         : symbolWidget),
                  ],
                ),
                4.verticalSpaceFromWidth,
                Row(
                  children: [
                    Expanded(
                      child: inputWidget,
                    ),
                    4.horizontalSpace,
                    Expanded(
                      child: orderInputWidget,
                    )
                  ],
                )
                // if (type != LocaleKeys.game.tr) inputWidget
              ],
            );
          }),
        ),
      ],
    );
  }

  Widget _buildInput(TextEditingController controller, String hintText) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 7.w)
          .copyWith(left: 12.w),
      decoration: BoxDecoration(
          border: Border(
              bottom: BorderSide(
                  color: AppColor.textPrimary.withOpacity(0.15), width: 1)),
          color: Colors.black.withOpacity(0.3),
          borderRadius: BorderRadius.circular(8.w)),
      child: Row(
        children: [
          Expanded(
              child: TextField(
            controller: controller,
            // maxLength: 20,
            style: TextStyle(
              fontSize: 14.sp,
              fontWeight: FontWeight.w500,
              color: AppColor.textPrimary.withOpacity(0.94),
            ),
            decoration: InputDecoration(
                border: InputBorder.none,
                enabledBorder: InputBorder.none,
                focusedBorder: InputBorder.none,
                disabledBorder: InputBorder.none,
                errorBorder: InputBorder.none,
                focusedErrorBorder: InputBorder.none,
                counterText: '',
                hintText: hintText,
                //LocaleKeys.enterMemberId.tr,
                isDense: true,
                // 紧凑布局，有助于垂直对齐
                hintStyle: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w400,
                  color: AppColor.textPrimary.withOpacity(0.5),
                ),
                contentPadding: EdgeInsets.zero,
                // 调整内边距
                isCollapsed: true),
            onSubmitted: (text) {
              logic.refreshController.requestRefresh();
            },
          )),
          GestureDetector(
            onTap: () {
              logic.refreshController.requestRefresh();
            },
            child: AutoImage(
              Assets.commonSearchBtn,
              width: 32.w,
            ),
          )
        ],
      ),
    );
  }

  Widget _buildTopDropdown(List<String> items,
      {required String value,
      required Function(String) onChanged,
      MainAxisAlignment? mainAxisAlignment,
      Color? btnColor}) {
    return BtnDropdown(
        items: items,
        value: value,
        // width: 1.sw - 32.w,

        mainAxisAlignment: mainAxisAlignment,
        onChanged: (value) {
          onChanged.call(value);
        },
        child: Container(
          padding: EdgeInsets.symmetric(horizontal: 10.w, vertical: 12.w),
          decoration: BoxDecoration(
              border: Border(
                  bottom: BorderSide(
                      color: AppColor.textPrimary.withOpacity(0.15), width: 1)),
              color: Colors.black.withOpacity(0.3),
              borderRadius: BorderRadius.circular(8.w)),
          child: Row(
            children: [
              Expanded(
                  child: Text(
                value,
                style: TextStyle(
                  fontSize: 14.sp,
                  fontWeight: FontWeight.w900,
                  color: btnColor ?? AppColor.textPrimary.withOpacity(0.94),
                ),
              )),
              AutoImage(
                Assets.promotionCommissionCaretDown,
                width: 16.w,
              )
            ],
          ),
        ));
  }

  String getGameType(ModelRecordTeamCommission team) {
    if (team.dataSource == 'third_party') {
      return LocaleKeys.funGame.tr;
    } else if (team.joinType == 1) {
      return LocaleKeys.externalTransfer.tr;
    } else {
      return LocaleKeys.internalBet.tr;
    }
  }
}
